package com.example.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.example.file.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
  * @Author: 贾明祯
  * @Date: 2021/1/26 9:41
  * @Introduce: webmvc自定义配置
  */
@Configuration
@ComponentScan
public class WebMvcConfig implements WebMvcConfigurer {
    //访问静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        String os = System.getProperty("os.name");
        registry.addResourceHandler("/PATH/**").addResourceLocations("file:///"+ FileUtil.getFilePath() +"/");
//        if(os.toLowerCase().startsWith("win")) {
//            registry.addResourceHandler("/wps/view/**").addResourceLocations("file:///"+WINDOWS_BASE_PATH+"/");
//        } else {
//            registry.addResourceHandler("/wps/view/**").addResourceLocations("file:///"+LINUX_BASE_PATH);
//        }
        // registry.addResourceHandler("/activiti/**").addResourceLocations("classpath:/static/activiti/");
/*        registry.addResourceHandler("/diagram-viewer/**").addResourceLocations("classpath:/static/activiti/diagram-viewer/");
        registry.addResourceHandler("/editor-app/**").addResourceLocations("classpath:/static/activiti/editor-app/");*/
//        registry.addResourceHandler("/view/**").addResourceLocations("classpath:/view/");
    }

    /* 视图跳转控制器 */
//    @Override
//    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController("/login").setViewName("login");
//        registry.addViewController("/index").setViewName("index");
//        registry.addViewController("/json/user").setViewName("/json/user.json");
//        registry.addViewController("/welcome").setViewName("home/welcome");
//        registry.addViewController("/swagger").setViewName("swagger-ui");
//        registry.addViewController("/swagger-ui").setViewName("swagger-ui");
//        registry.addViewController("/notice").setViewName("plugin/notice");
//        registry.addViewController("/dialog").setViewName("plugin/dialog");
//        registry.addViewController("/other").setViewName("plugin/other");
//    }
//    @Bean
//    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
//        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
//        registration.setMultipartConfig(multipartConfigElement());
//        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
//        return registration;
//    }

    /**
     *  fastjson序列化
     *需要将jackson依赖移除才能生效（缺点不能加入jackson，gson等，否则spring会自动装配）
     * */
   /* @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (int i = converters.size() - 1; i >= 0; i--) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.remove(i);
            }
        }
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");    // 自定义时间格式
        fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.BrowserCompatible, SerializerFeature.WriteNonStringKeyAsString
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter);
        converters.add(responseBodyConverter());
    }*/
    // 支持跨域访问
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息，
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize(DataSize.ofMegabytes(5000)); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(5000)); //3G
        // Sets the directory location where files will be stored.
        // factory.setLocation("路径地址");
        return factory.createMultipartConfig();
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

    /**
     * 配置消息转换器
     * new HttpMessageConverters(true, converters);
     * 一定要设为true才能替换否则不会替换
     * @return 返回一个消息转换的bean
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverter() {
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        //定义一个转换消息的对象
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(){
            @Override
            protected boolean supports(Class<?> clazz) {
                return clazz != String.class && super.supports(clazz);
            }
        };
        //添加fastjson的配置信息 比如 ：是否要格式化返回的json数据
        FastJsonConfig config = new FastJsonConfig();
 /*       config.setSerializerFeatures(
                SerializerFeature.WriteClassName,//是否在生成的json中输出类名
                SerializerFeature.WriteMapNullValue,//是否输出value为null的字符串
                SerializerFeature.PrettyFormat,//生成的json格式化
                SerializerFeature.WriteNullListAsEmpty,//空集合输出【】而非null
                SerializerFeature.WriteNullStringAsEmpty//空字符串输出“”而不是null
        );*/
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
         //全局时间配置
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setCharset(Charset.forName("UTF-8"));
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //在convert中添加配置信息.
        converter.setSupportedMediaTypes(fastMediaTypes);

        converter.setFastJsonConfig(config);
        converters.add(converter);
        return new HttpMessageConverters(true, converters);

      /*  config.setSerializeFilters(new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                if (value == null){
                    return "";
                }
                if (value instanceof Date){
                    return DateUtil.formatDate((Date) value,"yyyy-MM-dd hh:mm:ss");
                }
                return value;
            }
        });*/
        //在转换器中添加配置信息
    }
}
